import Taro from "@tarojs/taro";
import { posturl } from "./pathconfig";

function request(url, params, fn) {
  let info = Taro.getStorageSync("userinfo");
  if (info) {
    info = JSON.parse(info);
  }
  return Taro.request({
    url: posturl + url,
    method: "POST",
    data: params,
    header: {
      token: info.token ?? "",
      "content-type": "application/json" // 默认值
    },
    success: function(result) {
      fn && fn(result.data);
      if (result.data.code != "0000") {
        wx.showToast({
          title: result.data.msg,
          icon: "none",
          duration: 2000
        });
      }
    }
  });
}

function upload(filepath, extraparams, fn) {
  let info = Taro.getStorageSync("userinfo");
  if (info) {
    info = JSON.parse(info);
  }
  return Taro.uploadFile({
    url: posturl + "/ngic-base-business/sysAttachment/uploadFile", //仅为示例，非真实的接口地址
    filePath: filepath,
    name: "file",
    formData: extraparams ?? {},
    header: {
      token: info.token ?? ""
    },
    success(res) {
      const data = res.data;
      fn && fn(data);
      //do something
    }
  });
}

export { request, upload };
